/******************************************************************************
 * Author:      671643387
 * Created:     2016/9/27
 *****************************************************************************/

var mUtil = require('./util.js');
var ErrorCodes = require('./error.js').ErrorCodes;
var LaomaziRoom = require('./room.js').Room;
///////////////////////////////////////////////////////////////////////////////

function Laomazi() {
    this.roomIdGen = 99999;
    this.rooms = {};

    this.isStopping = false;
    //this.updates = {};
}
Laomazi.create = function(callback){
    var initLaomazi = {
        '_id':      'laomazi',
        //'rooms':    {},
    };
    gDBWorld.insert(initLaomazi, function(err, result){});
    callback && callback();
};
Laomazi.prototype = {
    init: function(callback) {
        gDBWorld.findOne({_id : 'laomazi'}, {}, function(err, doc){
            if( doc ) {
                //this.rooms = doc.rooms;

                // 更新房间
                var _me = this;
                setInterval(function () {
                    _me.update();
                }, 50);
                callback && callback(true);
            }else{
                callback && callback(false);
            }
        }.bind(this));
    },

    save: function(force, callback) {
        callback && callback(true);
    },

    update: function() {
        // 服务器在关闭
        if (this.isStopping) {
            return;
        }

        // 更新游戏房间
        var delKeys = [];

        for (var key in this.rooms) {
            if (!this.rooms.hasOwnProperty(key)) {
                continue;
            }
            if(this.rooms[key].update()) {
                delKeys.push(+key);
            }
        }

        // 删除已经销毁的房间
        delKeys.forEach(function(key){
            delete this.rooms[key];
        }.bind(this));
    },

    onServerShutdown: function(callback) {
        if (this.isStopping) {
            return;
        }
        this.isStopping = true;

        // 关闭所有房间
        for (var key in this.rooms) {
            if (!this.rooms.hasOwnProperty(key)) {
                continue;
            }
            this.rooms[key].onDestroy();
        }

        callback();
    },

    status: function(callback) {
        callback(null, {
            'totalRoom'     : Object.keys(this.rooms).length,
        });
    },

    ///////////////////////////////////////////////////////////////////////////

    // 创建房间
    createGame: function(uid, round, callback) {
        var newRoomId = Math.floor(Math.random() * this.roomIdGen);
        var creatorId = uid;
        var args = {
            'type': 'laomazi',
            'multiple': 1,
            'baseScore': 1,
            'totalRound': round,
        };
        this.rooms[newRoomId] = new LaomaziRoom(newRoomId, creatorId, args);
        callback(null, {
            roomId: newRoomId
        });
    },

    joinRoom: function(conn, roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        // 获取玩家数据
        getPlayerInfo(uid, function(player){
            if (!player) {
                callback(ErrorCodes.ERROR_QUERY_PLAYER_FAILED);
            } else {
                if (room.isFull() && !room.isPlayerInRoom(uid)) {
                    callback(ErrorCodes.ERROR_ROOM_IS_FULL);
                    return;
                }
                room.addPlayer(conn, uid, player, callback);
            }
        });
    },
    playerReady: function ( roomId, uid, callback ) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }
        // 获取玩家数据
        getPlayerInfo(uid, function(player){
            if (!player) {
                callback(ErrorCodes.ERROR_QUERY_PLAYER_FAILED);
            } else {
                if (room.isFull() && !room.isPlayerInRoom(uid)) {
                    callback(ErrorCodes.ERROR_ROOM_IS_FULL);
                    return;
                }

                room.playerReady(uid, callback);
            }
        });
    },

    destroyGame: function(conn, roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }
        room.destroy(uid, function (err) {
            callback(err);
        });
    },

    /**
     * 出牌
     */
    playCard: function(roomId, uid, cards, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.playCard(uid, cards, callback);
    },

    pass: function(roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.pass(uid, callback);
    },

    continue: function(roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.continue(uid, callback);
    },

    sendTipMsg: function(roomId, uid, msgId, msg, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.sendTipMsg(uid, msgId, msg, callback);
    },

    reqDestroyRoom: function(roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.reqDestroyRoom(uid, function (err) {
            callback(err);
        });
    },

    respDestroyRoom: function(roomId, uid, ok, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.respDestroyRoom(uid, ok, function (err) {
            callback(err);
        });
    },

    respExitRoom: function(roomId, uid, callback) {
        // 检查房间是否存在
        var room = this.rooms[roomId];
        if (!room || room.isDestroy()) {
            callback(ErrorCodes.ERROR_NO_SUCH_ROOM);
            return;
        }

        room.respExitRoom(uid, function (err) {
            callback(err);
        });
    },

};
exports.Laomazi = Laomazi;

///////////////////////////////////////////////////////////////////////////////
//>> 帮助函数

/**
 * 获取玩家数据
 * @param uid
 * @param callback
 */
function getPlayerInfo(uid, callback) {
    requestGame(uid, {}, 'laomazi', 'queryUser', function(resp){
        if (resp.code == 0) {
            callback(resp.data.player);
        } else {
            ERROR(resp.desc);
            callback(null);
        }
    });
}